<script setup>
import { getPageApi, updateUserStateApi,getByIdApi , getTreeApi ,updateApi ,saveApi, delApi} from "@/api/sysUser";
import { ElMessage, ElMessageBox } from "element-plus";
import $bus from "../../utils/bus";
import { onMounted, ref } from "vue";
// ---------------------------------------------------------------------获取查询---------------------------------------------------------------------
const dataList = ref([]);
const queryPageParams = ref({
  pageNumber: 1,
  pageSize: 10,
  userName: "",
});
const total = ref(0)
const selectedList = ref([])
const updateShow = ref(true)
const delShow = ref(true)
const getData = async () => {
  const res = await getPageApi(queryPageParams.value);
  dataList.value = res.data.list;
  total.value = res.data.total
};
const getPage = () => {
  getData();
};
const clear = () => {
  queryPageParams.value.pageNumber = 1;
  queryPageParams.value.pageSize = 10;
  queryPageParams.value.userName = "";
  getData();
};
const handleSelectionChange = (value) => {
  selectedList.value = value
  if(value.length==1){
    delShow.value = false
    updateShow.value = false
  }else if(value.length>1){
    updateShow.value = true
  }else{
    delShow.value = true
    updateShow.value = true
  }
 };
const switchHanler = async (id) => {
  // console.log(id);
  const res = await updateUserStateApi(id);
  console.log(res);
};
const handlePageChange = () => {
  getData()
}
// ---------------------------------------------------------------------添加修改---------------------------------------------------------------------
const open = ref(false)
const title = ref('弹出框dialog')
const formRef = ref(null)
const save = async () => {
  open.value = true
  title.value = '添加人员'
  const treeRes = await getTreeApi()
  treeList.value = treeRes.data
}
const form = ref({
  userAccount: '',
  userName: '',
  userNikename: '',
  userTel: ''
})
const formRule = ref({
  userAccount: [
    { required: true, message: "不能为空", trigger: "blur" },
    { min: 2, max: 20, message: "长度为2到20", trigger: "blur" },
  ],
  userName: [
    { required: true, message: "不能为空", trigger: "blur" },
    { min: 2, max: 20, message: "长度为2到20", trigger: "blur" },
  ],
  userNikename: [
    { required: true, message: "不能为空", trigger: "blur" },
    { min: 2, max: 20, message: "长度为2到20", trigger: "blur" },
  ],
  userTel: [
    { required: true, message: "不能为空", trigger: "blur" },
    { min: 11, max: 11, message: "电话为11位", trigger: "blur" },
  ],
  deptId: [
    { required: true, message: "部门不能为空", trigger: "blur" }
  ]
})
const props = ref({
  checkStrictly: true,
  multiple: false, // 启用多选
  //  emitPath: false, // 只返回该节点的值
  value: "id", // 自定义当前数组的键名 - value
  label: "deptName", // 自定义当前数组的键名 - label
  children: "children", // 自定义当前数组的键名 - children
  //  expandTrigger: "click", // 次级菜单的展开方式 - click/hover
  //  lazy: "false", // 是否动态加载子节点，需与 lazyLoad 方法结合使用
  //  lazyLoad: "false", // 加载动态数据的方法，仅在 lazy 为 true 时有效
})
const treeList = ref()
const colseReset = () => {
  form.value = {
    userAccount: '',
    userName: '',
    userNikename: '',
    userTel: '',
    deptId: 0
  }
}
const closeDialog = () => {
  open.value = false
  formRef.value.resetFields()
  colseReset()
}
const update = async (id) => {
  open.value = true
  title.value = '修改人员'
  // console.log(id)
  if(!id){
    id = selectedList.value[0].id
  }
  const res = await getByIdApi(id)
  form.value = res.data
  const treeRes = await getTreeApi()
  treeList.value = treeRes.data
}
const cascaderChange = (value) => {
  // console.log(value)
  // console.log(value[value.length - 1])
  form.value.deptId = value[value.length - 1]
}
const submit = () => {
  if (form.value.id) {
    formRef.value.validate(async (valid) => {
      if (!valid) {
        return
      }
      const res = await updateApi(form.value)
      ElMessage({
        message: res.data,
        type: "success",
      });
      getData()
      closeDialog()
    })
  } else {
    formRef.value.validate(async (valid) => {
      if (!valid) {
        return
      }
      const res = await saveApi(form.value)
      ElMessage({
        message: res.data,
        type: "success",
      });
      getData()
      closeDialog()
    })
  }
}
// ---------------------------------------------------------------------删除--------------------------------------------------------------------
const del = (id) => {
  if(!id){
    id = selectedList.value.map(item => item.id)
  }
  // console.log(id)
  ElMessageBox.confirm('确认删除？', '删除', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  }).then(async () => {
    const res = await delApi(id)
    ElMessage({
      type: 'success',
      message: res.data,
    })
    getData()
  }).catch(() => {
    ElMessage({
      type: 'info',
      message: '取消删除',
    })
  })
}
//---------------------------------------------------------------------获取标题事件---------------------------------------------------------------------
const titleData = ref({
  titleFir: "系统管理",
  titleSec: "用户管理",
});

onMounted(() => {
  $bus.emit("title-info", titleData.value);
  getData();
});
</script>

<template>
  <el-card>
    <el-form :inline="true" class="demo-form-inline">
      <el-form-item label="用户名称">
        <el-input placeholder="请输入用户名称" v-model="queryPageParams.userName" />
      </el-form-item>
      <el-form-item>
        <el-button icon="Search" type="primary" @click="getPage()">查询</el-button>
        <el-button icon="RefreshRight" type="info" @click="clear()">重置</el-button>
      </el-form-item>
      <br/>
      <el-form-item>
        <el-button icon="Plus" plain type="warning" @click="save()">添加</el-button>
        <el-button icon="Edit" plain :disabled="updateShow" type="success" @click="update()">修改</el-button>
        <el-button icon="Delete" plain :disabled="delShow" type="danger" @click="del()">删除</el-button>
      </el-form-item>
    </el-form>
  </el-card>

  <el-card>
    <!-- 数据展示表格 -->
    <el-table :data="dataList" @selection-change="handleSelectionChange" stripe fit>
      <el-table-column type="selection" width="55" align="center" />

      <el-table-column width="75" type="index" label="序号"></el-table-column>
      <el-table-column width="200" label="账号" prop="userAccount"></el-table-column>
      <el-table-column width="200" label="用户名" prop="userName"></el-table-column>
      <el-table-column width="200" label="昵称" prop="userNikename"></el-table-column>
      <el-table-column width="200" label="电话" prop="userTel"></el-table-column>
      <el-table-column width="150" label="部门" prop="deptName"></el-table-column>
      <el-table-column width="150" label="状态" prop="userState">
        <template #default="data">
          <el-switch size="large" v-model="data.row.userState" :value="data.row.userState" :active-value="1"
            :inactive-value="0" @change="switchHanler(data.row.id)"
            style="--el-switch-on-color: #13ce66; --el-switch-off-color: #ff4949" />
        </template>
      </el-table-column>
      <el-table-column width="150" label="等级" prop="userLev"></el-table-column>

      <el-table-column fixed="right" width="150" label="操作">
        <template #default="data">
          <el-button icon="Edit"  link type="success" size="small" @click="update(data.row.id)">修改</el-button>
          <el-button icon="Delete" link type="danger" size="small" @click="del(data.row.id)">删除</el-button>
        </template>
      </el-table-column>

    </el-table>

    <el-pagination
      v-model:current-page="queryPageParams.pageNumber"
      v-model:page-size="queryPageParams.pageSize"
      :page-sizes="[10, 50, 100, 200]"
      layout="total, sizes, prev, pager, next, jumper"
      :total="+total"
      @change="handlePageChange"
    />
  </el-card>
  <!-- :disabled="disabled" -->
      <!-- :background="background" -->
      <!-- @size-change="handleSizeChange" -->
      <!-- @current-change="handleCurrentChange" -->

  <!-- <el-card>
    <el-pagination
      v-model:current-page="currentPage4"
      v-model:page-size="pageSize4"
      :page-sizes="[100, 200, 300, 400]"
      :size="size"
      :disabled="disabled"
      :background="background"
      layout="total, sizes, prev, pager, next, jumper"
      :total="400"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
    />
  </el-card> -->

  <el-dialog v-model="open" :title="title" width="50%" :before-close="closeDialog" draggable>
    <el-form :model="form" label-width="auto" :rules="formRule" ref="formRef">
      <el-form-item label="账号" prop="userAccount">
        <el-input v-model="form.userAccount" />
      </el-form-item>
      <el-form-item label="用户名" prop="userName">
        <el-input v-model="form.userName" />
      </el-form-item>
      <el-form-item label="昵称" prop="userNikename">
        <el-input v-model="form.userNikename" prop="userNikename" />
      </el-form-item>
      <el-form-item label="电话" prop="userTel">
        <el-input v-model="form.userTel" />
      </el-form-item>
      <el-form-item label="部门" prop="deptId">
        <el-cascader v-model="form.deptId" placeholder="请选择部门" :options="treeList" :props="props"
          @change="cascaderChange" />
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="closeDialog()">取消</el-button>
        <el-button type="primary" @click="submit()">
          确定
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<style scoped lang="scss"></style>
